package com.sportsforce.client.twitter;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.maps.client.geom.LatLng;
import com.sportsforce.client.SportsForceTracking;
import com.sportsforce.client.map.Map;
import com.sportsforce.client.map.MapPointers;



/** 
 * Converts the information requested from Twitter API and convert them on the
 format necessary for the mapping feature.
 * 
 * @MainFeature 
 */
public class TweetList {

	public static void getTweets(Feed feed) {

		SportsForceTracking.vpMap.clear();

		boolean showMap = true;

		JsArray<Entry> entries = feed.getEntries();

		for (int i = 0; i < entries.length(); i++) {

			Entry entry = entries.get(i);
			JSONObject obj = new JSONObject(entry);

			String json = obj.toString();

			JSONValue text = obj.get("text");

			TweetEntity tweet = new TweetEntity();

			tweet.setTweetText(text.toString());

			if (obj.get("geo") != null) {

				try {

					JSONObject location = (JSONObject) obj.get("geo");

					JSONArray coordinates = (JSONArray) location
							.get("coordinates");

					double lat = Double.parseDouble(coordinates.get(0)
							.toString());
					double lon = Double.parseDouble(coordinates.get(1)
							.toString());

					tweet.setLatitude(lat);
					tweet.setLongitude(lon);

					LatLng us = LatLng.newInstance(lat, lon);

					if (showMap) {

						SportsForceTracking.vpMap.add(Map.getMap(us, 6));
						showMap = false;
					}
					new MapPointers(Map.map, tweet);

				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
	}

}

class Entry extends JavaScriptObject {
	protected Entry() {
	}

	public final native String getEntry() /*-{
		return this;
	}-*/;

	public final native String getText() /*-{
		return this.text;
	}-*/;

	public final native String getLocation() /*-{
		return this.geo;
	}-*/;

}

class Feed extends JavaScriptObject {
	protected Feed() {
	}

	public final native JsArray<Entry> getEntries() /*-{
		return this;
	}-*/;
}
